<script setup lang="ts">
import DepartmentTree from './components/DepartmentTree.vue';
import Users from './user/index.vue';
import { fetchDepartmentTree } from '@/api/endpoints/system/department';
import type { DepartmentWithChildren } from '@/api/endpoints/system/department';

const departmentTree = ref<DepartmentWithChildren[]>([]);
const selectedDepartment = ref<DepartmentWithChildren | null>(null);

onMounted(async () => {
  await loadDepartmentTree();
});

async function loadDepartmentTree() {
  try {
    const res = await fetchDepartmentTree();
    departmentTree.value = (res as any).data as DepartmentWithChildren[];
  } catch (error) {
    console.error('加载部门树失败:', error);
  }
}

function handleDepartmentSelect(department: DepartmentWithChildren) {
  selectedDepartment.value = department;
}

function handleDepartmentUpdate() {
  loadDepartmentTree();
}
</script>

<template>
  <div class="h-full flex">
    <!-- 左侧部门树 -->
    <div class="w-80 border-r border-border">
      <DepartmentTree
        :departments="departmentTree"
        :selected-department="selectedDepartment"
        @select="handleDepartmentSelect"
        @update="handleDepartmentUpdate"
      />
    </div>

    <!-- 右侧部门人员 -->
    <div class="flex-1">
      <!-- 头部 -->
      <div class="p-4 border-b border-border">
        <div class="flex items-center justify-between">
          <div class="flex gap-1 items-center">
            <h3 class="text-lg font-semibold">
              {{ selectedDepartment?.name || '请选择部门' }}
            </h3>
            <p class="text-sm text-muted-foreground">
              {{ selectedDepartment ? `0 名成员` : '选择左侧部门查看成员' }}
            </p>
          </div>
        </div>
      </div>

      <Users />
    </div>
  </div>
</template>
